﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using MammothMicro.SMTPGuard;
using MammothMicro.SMTPGuard.Common;
using MammothMicro.SMTPGuard.Filter;

namespace MammothMicro.SmtpGuardFilter.Filter
{
    /// <summary>
    /// Checks email for attachment type
    /// </summary>
    public class AttachmentFilter:IEmailFilter
    {
        private List<string> _list = new List<string>();

        #region IEmailFilter Members
    
        public bool Accept(MailMessage message)
        {
            if (message.Attachments.Count == 0)
                return true;

            var allowed = false;
            foreach (var attachment in message.Attachments)
            {
                allowed = _list.Exists(p => p.EndsWith(attachment.Name.Substring(attachment.Name.Length - 3).ToLower()));
            }

            return allowed;
        }

        public void Reload()
        {
            var path = Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

            var reader = new StreamReader(path.Remove(0,6) + @"\configuration\allowedAttachments.txt");
            var text = reader.ReadToEnd().ToLower();
            reader.Close();
            const string delimiter = "\r\n";
            var t = text.Split(delimiter.ToCharArray());

            _list = t.ToList();
            _list = Tools.ClearEmptyItems(_list);
        }


        #endregion
    }
}


